"use strict"
/**
 * @name draw
 * 抽卡
 */
const POINT = 100;
const { string } = require('assert-plus');
const { json } = require('body-parser');
const mvc = require('cosjs.mvc');
const random = mvc.library.require('random');
const DRAWKEY = "record.17";
/**
 * @name submit
 * @param int id 卡池id
 * @param int num 次数
 * 抽卡
 */
exports.submit = async function () {
    let id = this.get("id", "int");
    let num = this.get("num", "int");
    if (!id || !num) {
        return this.error("args empty");
    }
    //人物身上的卡池数据
    this.updater.role.key("draw");
    // this.updater.role.key("drawPoint");
    this.updater.role.key("totalDrawNum");
    this.updater.role.key("drawPool");
    let drawConfig = this.config("drawConfig", id);
    if (!drawConfig) {
        return this.error("config_not_exist", "drawType", id);
    }
    let drawConfigtype = this.config("drawConfigtype", drawConfig.type);
    if (!drawConfigtype) {
        return this.error("config_not_exist", drawConfig.type);
    }
    let costID = drawConfigtype.costID;
    return this.updater.data().then(async () => {
        //卡池数据
        // let addPoint = this.updater.role.get("drawPoint."+drawConfig.type);
        let drawData = this.updater.role.get("draw." + drawConfig.type) || { "drawTime": 0, "addPoint": 0 };//当前时间
        let totalDrawNum = this.updater.role.get("totalDrawNum");
        let drawPool = this.updater.role.get('drawPool.' + id) || 0;
        let drawLimit = drawConfig.drawConfigtimes;
        if (drawLimit && drawPool && drawPool >= drawLimit) {
            return this.error("该卡池已达到抽卡次数上限", id);
        }
        if (drawLimit && drawPool + num > drawLimit) {
            return this.error('该卡池已达到抽卡次数上限', id);
        }
        if (totalDrawNum >= 50 || totalDrawNum < 0) {
            totalDrawNum = 0;
        }
        // let nowTime = this.updater.time;
        //结果列表
        let flag = false;
        if (num == 10) {
            //抽卡券十连
            for (var i = 0; i < num; i++) {
                // if (totalDrawNum == 49) {
                //     //当抽卡次数累计50 ，必出3星
                //     let data = await mustThreeStar.call(this, id, drawData);
                //     drawData = data.drawData;
                //     totalDrawNum = 0;
                //     continue;
                // }
                if (flag == false && (i == (num - 1))) {
                    let data = await drawReward.call(this, id, drawData, true);
                    drawData = data.drawData;
                    totalDrawNum++;
                    // flag = data.upFlag;
                } else {
                    let data = await drawReward.call(this, id, drawData, false);
                    drawData = data.drawData;
                    flag = data.upFlag;
                    totalDrawNum++;
                }

            }
            this.updater.daily.add(DRAWKEY, 10);
            this.updater.record.add(17, 10);
        } else {
            //抽卡券N连
            for (var i = 0; i < num; i++) {
                // if (totalDrawNum == 49) {
                //     //当抽卡次数累计50 ，必出3星
                //     let data = await mustThreeStar.call(this, id, drawData);
                //     drawData = data.drawData;
                //     totalDrawNum = 0;
                //     continue;
                // }
                let data = await drawReward.call(this, id, drawData, false);
                drawData = data.drawData;
                totalDrawNum++;

            }
            this.updater.daily.add(DRAWKEY, num);
            this.updater.record.add(17, num);
        }
        //更新卡池对象
        this.updater.sub(costID, num);
        if (parseInt(drawConfigtype.reward)) {
            this.updater.add(drawConfigtype.reward, num);
        }

        this.updater.role.set("drawPool." + id, num + drawPool);
        this.updater.role.set("draw." + drawConfig.type, drawData);
        this.updater.role.set("totalDrawNum", totalDrawNum);
        return this.updater.save();
    });
}


//单抽统一接口
//每一抽都是基于上一抽的数据
//参数 卡池ID  卡池数据  本次抽卡是否需要保底2星
async function drawReward() {
    let id = arguments[0];      //卡池ID
    let drawData = arguments[1];//卡池数据
    let upFlag = arguments[2];//本次抽卡是否需要保底2星
    let addPoint = drawData.addPoint || 0;//增加的Up概率
    drawData.drawTime++;
    let drawConfig = this.config("drawConfig", id);
    if (!drawConfig) {
        return this.error("config_not_exist", "drawConfig", id);
    }
    let drawConfigtype = this.config('drawConfigtype', drawConfig.type);
    if (!drawConfigtype) {
        return this.error("config_not_exist", "drawConfigtype", drawConfig.type);
    }
    //先随出1星，2星，3星
    let drawPoolConfig = this.config("drawPoolConfig", id);
    if (!drawPoolConfig) {
        return this.error("config_not_exist", "drawPoolConfig", id);
    }
    let localRate = [{}, {}, {}];
    for (let v of drawPoolConfig.Coll) {
        localRate[v.type - 1] = JSON.parse(JSON.stringify(v));
    }
    // for(let i = 0;i<2;i++){
    //     if(localRate[i].rate<0){
    //         localRate[i+1].rate -=addPoint;
    //     }
    // }
    localRate[0].rate -= addPoint;
    if (localRate[0] < 0) {
        localRate[1].rate += localRate[1].rate;
    }
    localRate[2].rate += addPoint;
    for (let i = 0; i < 3; i++) {
        if (localRate[i].rate < 0) {
            localRate[i].rate = 0;
        }
    }
    //1的概率和2的概率合并
    if (upFlag) {
        localRate[1].rate += localRate[0].rate;
        localRate[0].rate = 0;
    }
    // let poolID = 0;
    //通过概率计算出货组
    // console.log("本次出卡概率：", localRate[0], localRate[1], localRate[2]);
    let k = random.Relative(localRate, 'rate');
    if (k === false) {
        return this.quick_error("M2HS4", "卡池配置不匹配",);
    }
    if (k == 0) {
        //出1星
        // console.log("一星");
    } else if (k == 1) {
        //出2星
        // console.log("二星");
        upFlag = true;
    } else {
        //出3星
        // console.log("三星重置点数", drawData.addPoint, drawData.drawTime);
        drawData.drawTime = 0;
        drawData.addPoint = 0;
    }
    if (drawData.drawTime >= drawConfigtype.addRateNum) {
        drawData.addPoint += drawConfigtype.addRate;
        // console.log("增加概率点数", drawData.addPoint, drawData.drawTime);
    }
    //去对应星级里随机找角色
    let { err, ret } = this.updater.item.group(localRate[k].groupID);
    if (err) {
        return this.error(err, ret);
    } else {
        //redis写入抽卡记录
        let drawCache = this.model.redis("drawCache", this.sid, this.uid + ":" + drawConfig.type);
        // let ttl = 90 * 24 * 3600; //有效期1天
        let unitInfo = { unitGetTime: Date.now(), unitID: ret.id };
        drawCache.push(JSON.stringify(unitInfo), (err) => {
            if (err) throw err;
            drawCache.trim(0, 99, (err) => {
                if (err) throw err;
            })
        });
    }
    return { 'upFlag': upFlag, 'drawData': drawData };
}

//累计50抽
//第50抽，必出三星
// async function mustThreeStar() {
//     let id = arguments[0]; //卡池ID
//     let drawData = arguments[1];//卡池数据
//     drawData.drawTime++;
//     let drawConfig = this.config("drawConfig", id);
//     if (!drawConfig) {
//         return this.error("config_not_exist", "drawConfig", id);
//     }
//     let drawPoolConfig = this.config("drawPoolConfig", id);
//     if (!drawPoolConfig) {
//         return this.error("config_not_exist", "drawPoolConfig", id);
//     }
//     let threeStar = JSON.parse(JSON.stringify(drawPoolConfig.Coll[0]));

//     //去三星级里随机找角色
//     let { err, unit } = this.updater.item.group(threeStar.groupID);

//     if (err) {
//         return this.error(err, unit);
//     }
//     return { 'drawData': drawData };
// }

/**
 * @name getDrawRecordListFromRedis
 * @param string id 玩家uid
 * @param int drawType 卡池类型
 * 获取抽卡记录
 */
exports.getDrawRecordListFromRedis = async function () {
    let id = this.get('id', 'string');
    let drawType = this.get('drawType', 'int');
    if (!id || !drawType) {
        return this.quick_error('args empty');
    }

    //获取key值
    let drawCache = this.model.redis("drawCache", this.sid, id + ":" + drawType);
    if (!drawCache) {
        return this.quick_error('无法获取key值');
    }
    return drawCache.range(0, -1).then(ret => {
        if (!ret) reject('记录不存在！');
        return ret;

    });
}